package com.zhangsheng.util;

import com.zhangsheng.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

/**
 * @author 张晟
 * @version 1.0
 * @date 2024/3/3 16:55
 */
@Slf4j
@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessageToOrderExchange(@NonNull Integer orderId, String delayTime){
        log.info("死信队列模式发送消息");
        rabbitTemplate.convertAndSend(RabbitConfig.orderExchange, RabbitConfig.orderRoutingKey, orderId, message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            messageProperties.setExpiration(delayTime);
            return message;
        });
    }

    public void sendMessageToDelayExchange(@NonNull Integer orderId, Integer delayTime){
        log.info("延迟队列模式发送消息");
        rabbitTemplate.convertAndSend(RabbitConfig.delayExchange, RabbitConfig.delayRoutingKey, orderId, message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setMessageId(String.valueOf(orderId));
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            messageProperties.setDelay(delayTime);
            return message;
        });
    }

}
